#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from public.project_patch import CONFIG_YAML, SERVER_YAML
from utils.yaml_util import YamlHandler


class TestContext:
    __instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = object.__new__(cls, *args)
        return cls.__instance

    def __init__(self):
        self.global_dict = {}
        self.env_config = YamlHandler(CONFIG_YAML).read_yaml()
        self.server_yaml = YamlHandler(SERVER_YAML).read_yaml()
        self.env = self.env_config["env"]
        self.region = self.env_config[self.env]["region"]
        self.zone = self.env_config[self.env]["zone"][0]
        self.login_url = self.env_config[self.env]["login_url"]
        self.base_url = self.env_config[self.env]["base_url"]
        self.console_url = self.base_url.rstrip("/")
        self.language = self.env_config[self.env]["language"]
        self.account = self.env_config[self.env]["account"]
        self.username = self.account["user"]
        self.password = self.account["pwd"]
        self.ak = self.env_config[self.env]["qy_access_key_id"]
        self.sk = self.env_config[self.env]["qy_secret_access_key"]
        self.api_host = self.env_config[self.env]["api_host"]
        self.port = self.env_config[self.env]["port"]
        self.protocol = self.env_config[self.env]["protocol"]

    def get_server_yaml_config(self, key=None):
        """获取server yaml配置文件"""
        if key is not None:
            return self.server_yaml[self.env].get(key, {})
        return self.server_yaml[self.env]

    def get_server_yaml_config_from_common(self, key=None):
        """获取server yaml 中common中的配置"""
        return self.get_server_yaml_config().get("common", {}).get(key, {})

    def set_value(self, key, value):
        """添加全局变量"""
        self.global_dict[key] = value

    def get_value(self, key, def_val=None):
        """获取某个全局变量"""
        try:
            return self.global_dict.get(key)
        except KeyError:
            return def_val

    def get_values(self):
        """获取全部全局变量"""
        return self.global_dict

    def delete_value(self, key):
        """删除某个全局变量"""
        self.global_dict.pop(key)

    def clean_values(self):
        """清空全局变量"""
        self.global_dict.clear()

    def delete_values(self):
        """删除全局变量"""
        del self.global_dict


ctx = TestContext()

__all__ = ["ctx"]
